package com.oss.service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.jdo.JDOObjectNotFoundException;
import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import com.oss.PMF;
import com.oss.model.Topic;

/**
 * @author xueqiang.mi
 * @since 2010-8-2
 */
public class TopicService extends BaseService {

	public void add(Topic obj) {
		PersistenceManager pm = PMF.get();
		try {
			obj.setId(generateId(obj.getName()));

			if (isExist(obj.getId())) {
				return;
			}
			pm.makePersistent(obj);
		} finally {
			pm.close();
		}
	}

	public Topic get(String id) {
		PersistenceManager pm = PMF.get();
		try {
			Topic obj = pm.getObjectById(Topic.class, id);
			return obj;
		} catch (JDOObjectNotFoundException e) {
			return null;
		} finally {
			pm.close();
		}
	}

	@SuppressWarnings("unchecked")
	public List<Topic> getTopics(long pageIndex, long pageSize) {
		PersistenceManager pm = PMF.get();
		try {
			Query query = pm.newQuery(Topic.class);
			query.setRange((pageIndex - 1) * pageSize, pageIndex * pageSize);
			Collection<Topic> c = pm.detachCopyAll((Collection<Topic>) query.execute());
			return new ArrayList<Topic>(c);
		} finally {
			pm.close();
		}
	}

	@SuppressWarnings("unchecked")
	public List<Topic> getHottestTopics(long pageIndex, long pageSize) {
		PersistenceManager pm = PMF.get();
		try {
			Query query = pm.newQuery(Topic.class);
			query.setOrdering("linkQuantity desc");
			query.setRange((pageIndex - 1) * pageSize, pageIndex * pageSize);
			Collection<Topic> c = pm.detachCopyAll((Collection<Topic>) query.execute());
			return new ArrayList<Topic>(c);
		} finally {
			pm.close();
		}
	}

	private boolean isExist(String id) {
		return get(id) != null;
	}

	public void save(Topic topic) {
		PersistenceManager pm = PMF.get();
		try {
			pm.makePersistent(topic);
		} finally {
			pm.close();
		}
	}

}
